<template>
  <div class="course-image">
    <el-progress
      v-if="isUploading"
      type="circle"
      :percentage="percentage"
      :width="178"
      :status="percentage === 100 ? 'success' : undefined"
    />
    <el-upload
      v-else
      class="avatar-uploader"
      action="/post"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="handleUpload"
    >
      <img
        v-if="modelValue"
        :src="modelValue"
        class="avatar"
      >
      <i
        v-else
        class="el-icon-plus avatar-uploader-icon"
      />
    </el-upload>
  </div>
</template>

<script lang="ts">
import { ElMessage } from 'element-plus'
import { defineComponent, ref } from 'vue'
import { uploadCourseImage } from '/@/services/course'

export default defineComponent({
  name: 'CourseImage',
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    limit: {
      type: Number,
      default: 2
    }
  },
  emits: ['update:modelValue'],
  setup (props, { emit }) {
    const isUploading = ref(false)
    const percentage = ref(0)
    const beforeAvatarUpload = (file: any) => {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < props.limit

      if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error(`上传头像图片大小不能超过 ${props.limit}MB!`)
      }
      return isJPG && isLt2M
    }

    const handleUpload = async (options: any) => {
      try {
        isUploading.value = true
        const fd = new FormData()
        fd.append('file', options.file)
        const { data } = await uploadCourseImage(fd, e => {
          percentage.value = Math.floor(e.loaded / e.total * 100)
        })
        if (data.code === '000000') {
          isUploading.value = false
          percentage.value = 0
          emit('update:modelValue', data.data.name)
        } else {
          ElMessage.error('上传失败')
        }
      } catch (err) {
        console.log(err)
      }
      isUploading.value = false
      percentage.value = 0
    }
    return {
      isUploading,
      percentage,
      beforeAvatarUpload,
      handleUpload
    }
  }
})
</script>

<style lang="scss" scoped>
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
